﻿using System;
using System.Collections.Generic;
using System.IO;

namespace Borg.Framework
{
    public class ExecuteCommand : ICommand
    {
        private readonly CommandInterpreter _cmdInterpreter;

        public ExecuteCommand(CommandInterpreter ci)
        {
            _cmdInterpreter = ci;
        }

        private string Execute(string[] command)
        {
            if (command.Length < 2)
                return string.Format("Command file argument is missing.", new object[0]);

            if (!File.Exists(command[1]))
                return string.Format("File \"{0}\" does not exist.", command[1]);

            try
            {
                using (var reader = new StreamReader(command[1]))
                {
                    string cmd;

                    while ((cmd = reader.ReadLine()) != null)
                        _cmdInterpreter.Execute(cmd);
                }
            }
            catch
            {
                return string.Format("File \"{0}\"  could not be read.", command[1]);
            }

            return string.Empty;
        }

        public IEnumerable<string> GetArguments(string[] command, int pos)
        {
            if (pos != 0)
                return null;

            var list = new List<string>();

            list.AddRange(Directory.GetFiles(
                Environment.CurrentDirectory, "*.cmds", SearchOption.AllDirectories));

            var startIndex = Environment.CurrentDirectory.Length + 1;

            for (var i = 0; i < list.Count; i++)
                list[i] = list[i].Substring(startIndex);

            return list;
        }

        public CommandHandler Handler
        {
            get { return Execute; }
        }

        public string Help
        {
            get { return null; }
        }

        public string Name
        {
            get { return "execute"; }
        }
    }
}

